package com.mindcraft.user.serivce.impl;


import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mindcraft.base.handle.MindCraftRuntimeException;
import com.mindcraft.base.model.MindCraftResult;
import com.mindcraft.base.utils.CommonConst;
import com.mindcraft.user.Dto.LoginDto;
import com.mindcraft.user.mapper.McUserMapper;
import com.mindcraft.user.po.McUser;
import com.mindcraft.user.serivce.UserService;
import com.mindcraft.user.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author sara
 * @since 2021-08-12
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<McUserMapper, McUser> implements UserService {


    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public MindCraftResult<UserVO> login(LoginDto loginDto) {
        String password = null;
        password = new String(SecureUtil.aes(CommonConst.CRYPOTJS_KEY.getBytes(StandardCharsets.UTF_8)).decrypt(loginDto.getPassword()));

        McUser one = lambdaQuery().and(wrapper -> wrapper
                        .eq(McUser::getUsername, loginDto.getAccount())
                        .or()
                        .eq(McUser::getEmail, loginDto.getAccount()))
                .eq(McUser::getPassword, DigestUtils.md5DigestAsHex(password.getBytes()))
                .one();

        if (one == null) {
            return MindCraftResult.fail("账号/密码错误，请重新输入！");
        }

        if (!one.getStatus().equals("1")) {
            return MindCraftResult.fail("账号被冻结！");
        }

        String userToken = "";


        if (redisTemplate.opsForValue().get(CommonConst.USER_TOKEN + one.getId()) != null) {
            userToken = (String) redisTemplate.opsForValue().get(CommonConst.USER_TOKEN + one.getId());
        }


        if (!StringUtils.hasText(userToken)) {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            userToken = CommonConst.USER_ACCESS_TOKEN + uuid;

            redisTemplate.opsForValue().set(userToken, one, CommonConst.TOKEN_EXPIRE, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set(CommonConst.USER_TOKEN + one.getId(), userToken, CommonConst.TOKEN_EXPIRE, TimeUnit.SECONDS);
        }


        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(one, userVO);
        userVO.setPassword(null);


        userVO.setAccessToken(userToken);

        return MindCraftResult.success(userVO);
    }

    @Override
    public MindCraftResult exit(String usertoken) {

        Boolean result = redisTemplate.delete(usertoken);
        if (result) {
            // 删除成功
            return MindCraftResult.success();
        } else {
            // 删除失败
            return MindCraftResult.fail("退出失败");
        }

    }

    @Override
    public MindCraftResult<UserVO> regist(UserVO user) {
//        String regex = "\\d{11}";
//        if (user.getUsername().matches(regex)) {
//            return MindCraftResult.fail("用户名不能为11位数字！");
//        }
//
//        if (user.getUsername().contains("@")) {
//            return MindCraftResult.fail("用户名不能包含@！");
//        }
//
//        if (StringUtils.hasText(user.getPhoneNumber()) && StringUtils.hasText(user.getEmail())) {
//            return MindCraftResult.fail("手机号与邮箱只能选择其中一个！");
//        }
//
//        if (StringUtils.hasText(user.getPhoneNumber())) {
//            Integer codeCache = (Integer) MindCraftCache.get(CommonConst.FORGET_PASSWORD + user.getPhoneNumber() + "_1");
//            if (codeCache == null || codeCache != Integer.parseInt(user.getCode())) {
//                return MindCraftResult.fail("验证码错误！");
//            }
//            MindCraftCache.remove(CommonConst.FORGET_PASSWORD + user.getPhoneNumber() + "_1");
//        } else if (StringUtils.hasText(user.getEmail())) {
//            Integer codeCache = (Integer) MindCraftCache.get(CommonConst.FORGET_PASSWORD + user.getEmail() + "_2");
//            if (codeCache == null || codeCache != Integer.parseInt(user.getCode())) {
//                return MindCraftResult.fail("验证码错误！");
//            }
//            MindCraftCache.remove(CommonConst.FORGET_PASSWORD + user.getEmail() + "_2");
//        } else {
//            return MindCraftResult.fail("请输入邮箱或手机号！");
//        }
//
//
//        user.setPassword(new String(SecureUtil.aes(CommonConst.CRYPOTJS_KEY.getBytes(StandardCharsets.UTF_8)).decrypt(user.getPassword())));
//
//        Integer count = lambdaQuery().eq(User::getUsername, user.getUsername()).count();
//        if (count != 0) {
//            return MindCraftResult.fail("用户名重复！");
//        }
//        if (StringUtils.hasText(user.getPhoneNumber())) {
//            Integer phoneNumberCount = lambdaQuery().eq(User::getPhoneNumber, user.getPhoneNumber()).count();
//            if (phoneNumberCount != 0) {
//                return MindCraftResult.fail("手机号重复！");
//            }
//        } else if (StringUtils.hasText(user.getEmail())) {
//            Integer emailCount = lambdaQuery().eq(User::getEmail, user.getEmail()).count();
//            if (emailCount != 0) {
//                return MindCraftResult.fail("邮箱重复！");
//            }
//        }
//
//        User u = new User();
//        u.setUsername(user.getUsername());
//        u.setPhoneNumber(user.getPhoneNumber());
//        u.setEmail(user.getEmail());
//        u.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
//        u.setAvatar(MindCraftUtil.getRandomAvatar(null));
//        save(u);
//
//        User one = lambdaQuery().eq(User::getId, u.getId()).one();
//
//        String userToken = CommonConst.USER_ACCESS_TOKEN + UUID.randomUUID().toString().replaceAll("-", "");
//        MindCraftCache.put(userToken, one, CommonConst.TOKEN_EXPIRE);
//        MindCraftCache.put(CommonConst.USER_TOKEN + one.getId(), userToken, CommonConst.TOKEN_EXPIRE);
//
//        UserVO userVO = new UserVO();
//        BeanUtils.copyProperties(one, userVO);
//        userVO.setPassword(null);
//        userVO.setAccessToken(userToken);
//
//        WeiYan weiYan = new WeiYan();
//        weiYan.setUserId(one.getId());
//        weiYan.setContent("到此一游");
//        weiYan.setType(CommonConst.WEIYAN_TYPE_FRIEND);
//        weiYan.setIsPublic(Boolean.TRUE);
//        weiYanService.save(weiYan);
//
//        ImChatGroupUser imChatGroupUser = new ImChatGroupUser();
//        imChatGroupUser.setGroupId(ImConfigConst.DEFAULT_GROUP_ID);
//        imChatGroupUser.setUserId(one.getId());
//        imChatGroupUser.setUserStatus(ImConfigConst.GROUP_USER_STATUS_PASS);
//        imChatGroupUserMapper.insert(imChatGroupUser);
//
//        ImChatUserFriend imChatUser = new ImChatUserFriend();
//        imChatUser.setUserId(one.getId());
//        imChatUser.setFriendId(MindCraftUtil.getAdminUser().getId());
//        imChatUser.setRemark("站长");
//        imChatUser.setFriendStatus(ImConfigConst.FRIEND_STATUS_PASS);
//        imChatUserFriendMapper.insert(imChatUser);
//
//        ImChatUserFriend imChatFriend = new ImChatUserFriend();
//        imChatFriend.setUserId(MindCraftUtil.getAdminUser().getId());
//        imChatFriend.setFriendId(one.getId());
//        imChatFriend.setFriendStatus(ImConfigConst.FRIEND_STATUS_PASS);
//        imChatUserFriendMapper.insert(imChatFriend);

//        return MindCraftResult.success(userVO);
        return MindCraftResult.success();
    }


    @Override
    public MindCraftResult<UserVO> token(String userToken) {
//        userToken = new String(SecureUtil.aes(CommonConst.CRYPOTJS_KEY.getBytes(StandardCharsets.UTF_8)).decrypt(userToken));

        if (!StringUtils.hasText(userToken)) {
            throw new MindCraftRuntimeException("未登陆，请登陆后再进行操作！");
        }
        log.info(userToken);
        McUser user = (McUser) redisTemplate.opsForValue().get(userToken);

        if (user == null) {
            throw new MindCraftRuntimeException("登录已过期，请重新登陆！");
        }

        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setPassword(null);

        userVO.setAccessToken(userToken);

        return MindCraftResult.success(userVO);
    }


}
